package cn.hubujyjs.lp.service.impl;


import cn.hubujyjs.lp.constant.FileUnit;
import cn.hubujyjs.lp.domain.File;
import cn.hubujyjs.lp.mapper.FileMapper;
import cn.hubujyjs.lp.service.FileService;
import cn.hubujyjs.lp.utils.R;
import cn.hubujyjs.lp.vo.FileStatistics;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Builder;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
* @author admin
* @description 针对表【file】的数据库操作Service实现
* @createDate 2023-05-17 18:14:30
*/
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File>
    implements FileService {
    @Value("${lp.path}")
    private String basePath;
    @Override
    public R<String> preview(Integer fileId) {
        File byId = this.getById(fileId);
        String path = byId.getPath();
        String filepath=basePath+path;
        String templateContent;
        try {
            templateContent=getTemplateContent(filepath);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return R.ok(templateContent);
    }

    @Override
    public R<String> download(Integer fileId) {
        File byId = this.getById(fileId);
        return R.ok(byId.getUrl());
    }

    /**
     * 文件统计
     * @return FileStatistics
     */
    @Override
    public R<FileStatistics> statistics() {
        List<File> list = this.list();
        long filesCount = list.size();
        long filesSize = list.stream().mapToLong(File::getSize).sum();
        long todayFilesCount = list.stream().filter(this::extracted).count();
        long todayFilesSize = list.stream().filter(this::extracted).mapToLong(File::getSize).sum();

        SizeWithUnit sizeWithUnit = sizeToFileSize(filesSize);
        SizeWithUnit todaySizeWithUnit = sizeToFileSize(todayFilesSize);
        FileStatistics build = FileStatistics.builder()
                .filesSize(sizeWithUnit.fileSize)
                .filesCount(filesCount)
                .todayFilesCount(todayFilesCount)
                .todayFilesSize(todaySizeWithUnit.fileSize)
                .fileSizeUit(sizeWithUnit.fileUnit)
                .todayFilesSizeUnit(todaySizeWithUnit.fileUnit)
                .build();
        return R.ok(build);
    }

    /**
     * 判断文件是否是今天的
     * @param i 文件
     * @return 是否是今天的文件
     */
    private boolean extracted(File i) {
        String today = DateUtil.today();
        Date updateTime = i.getUpdateTime();
        String pattern = "yyyy-MM-dd";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        String format = simpleDateFormat.format(updateTime);
        return today.equals(format);
    }
    @Builder
    @Data
    static class SizeWithUnit{
        Double fileSize;
        FileUnit fileUnit;
    }
    /**
     * 单位转换
     * @return 数据和单位
     */
    public SizeWithUnit sizeToFileSize(Long size){
        Double newSize= Double.valueOf(size);
        if (newSize < 1024) {
            return SizeWithUnit.builder()
                    .fileSize(newSize)
                    .fileUnit(FileUnit.B)
                    .build();
        } else {
            newSize = newSize / 1024;
        }
        if (newSize < 1024) {
            return SizeWithUnit.builder()
                    .fileSize(newSize)
                    .fileUnit(FileUnit.KB)
                    .build();
        } else {
            newSize = newSize / 1024;
        }
        if (newSize < 1024) {
            return SizeWithUnit.builder()
                    .fileSize(newSize)
                    .fileUnit(FileUnit.MB)
                    .build();
        } else {
            return SizeWithUnit.builder()
                    .fileSize(newSize)
                    .fileUnit(FileUnit.GB)
                    .build();
        }
    }

    private String getTemplateContent(String filepath) throws Exception{
        java.io.File file = new java.io.File(filepath);
        if(!file.exists()){
            return null;
        }
        FileInputStream inputStream = new FileInputStream(file);
        int length = inputStream.available();
        byte[] bytes = new byte[length];
        inputStream.read(bytes);
        inputStream.close();
        String str =new String(bytes, StandardCharsets.UTF_8);
        return str;
    }
}




